<?php

namespace App\Services;

use App\Exceptions\InternalException;
use App\Models\Project;
use App\Models\ProjectCost;
use App\Models\ProjectInvoice;
use App\Models\ProjectOther;
use App\Models\ProjectPresent;
use App\Models\ProjectUser;
use App\Models\Role;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class ProjectService
{
    public function get($search){
        $sql = Project::with('users')->withCount('users')->when($search, function ($query, $search) {
            return $query->where(function($query) use ($search) {
                $query->where('title','like', '%'.$search.'%');
            });
        });

        return $sql;
    }

    public function processess($search){
        $sql = Project::select('id','title','status')->with('processess')->when($search, function ($query, $search) {
            return $query->where(function($query) use ($search) {
                $query->where('title','like', '%'.$search.'%');
            });
        });

        return $sql;
    }

    public function projectIsUser($project_id){
        $project = Project::with('users')->where('id',$project_id)->first();
        $id = [];
        foreach ($project->users as $key => $value) {
            $id[] = $value->id;
        }
        $users = User::where('id','>',1)->get();
        foreach ($users as $key => $value) {
            $users[$key]->is_select = false;
            if(in_array($value->id,$id)){
                $users[$key]->is_select = true;
            }
        }
        return $users;
    }

    public function getProjectUsers($project_id){
        $role = Role::whereIn('project_id',[0,$project_id])->get();
        $project = ProjectUser::with('user')->with('cert')->with('role')->where('project_id',$project_id)->get();
        foreach ($project as $key => $value) {
            $project[$key]->role_name = $role->whereIn('id',json_decode($value->roles))->pluck('name');
        }
        return $project;
    }

    public function getUsers($project_id){
        $project = Project::with('users')->where('id',$project_id)->first();
        $users = $project->users;
        $roleId = [];
        foreach ($users as $key => $value) {
            $roleId[] = $value->pivot->role_id;
        }
        $role = Role::whereIn('id',$roleId)->get();
        foreach ($users as $key => $value) {
            $is = $role->where('id',$value->pivot->role_id)->first();
            $users[$key]->role_name = empty($is) ? '' : $is->name;
        }
        return $users;
    }

    public function getUser($project_id,$id){
        $project = Project::with(['users' => function ($query) {
            $query->select('project_users.*'); // 选择中间表的字段
        }])->where('id',$project_id)->first();
        $user = User::with('certs')->find($id);
        foreach ($project->users as $k => $v) {
            if($id == $v->user_id){
                $v->certs = $user->certs;
                return $v;
            }
        }
        return [];
    }

    public function getRoleUsers($id){
        $project = Project::with('users')->where('id',$id)->first();
        $users = $project->users;
        $users = $users->groupBy('role_id');
        $role_id = [];
        foreach ($users as $k => $v) {
            $role_id[] = $k;
        }
        $role = Role::select('id','name','status')->with('users')->whereIn('id',$role_id)->get();
        return $role;
    }

    public function insert($input,$other){
        $res = [];
        foreach ($input as $k => $v) {
            if($v){
                $res[$k] = $v;
            }
        }

        try {
            $data = Project::create($res);
            if($data){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function update($input,$other=''){
        try {
            $data = Project::find($input['id']);
            foreach ($input as $k => $v) {
                $data->$k = $v;
            }
            $data->save();
            return $data;
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function updateSummary($input){
        $res = [];
        foreach ($input as $k => $v) {
            $v = $v === null ? '/' : $v;
            if($v){
                $res[$k] = $v;
            }
        }
        unset($res['id']);
        unset($res['project_id']);
        try {
            $data = Project::where('id',$input['id'])->update($res);
            if($data){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }



    public function insertProjectInvoice($input){
        $res = [];
        foreach ($input as $k => $v) {
            $v = $v === null ? '/' : $v;
            if($v){
                $res[$k] = $v;
            }
        }
        unset($res['id']);
        try {
            $data = ProjectInvoice::create($res);
            if($data){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function updateProjectInvoice($input){
        try {
            $data = ProjectInvoice::find($input['id']);
            foreach ($input as $k => $v) {
                $data->$k = $v;
            }
            $data->save();
            return $data;
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }



    public function invoiceReviewer($input){
        $res = [];
        foreach ($input as $k => $v) {
            $v = $v === null ? '/' : $v;
            if($v){
                $res[$k] = $v;
            }
        }
        unset($res['id']);
        try {
            $data = ProjectInvoice::where('id',$input['id'])->update($res);
            if($data){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function projectBindUser($input){
        $user = Project::find($input['project_id']);
        $users = json_decode($input['users']);
        try {
            $user->users()->sync($users);
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function insertPresent($input){
        $res = [];
        foreach ($input as $k => $v) {
            if($v){
                $res[$k] = $v;
            }
        }

        try {
            $data = ProjectPresent::create($res);
            if($data){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function updatePresent($input,){
        $res = [];
        foreach ($input as $k => $v) {
            $v = $v === null ? '/' : $v;
            if($v){
                $res[$k] = $v;
            }
        }

        unset($res['id']);
        try {
            $data = ProjectPresent::where('id',$input['id'])->update($res);
            if($data){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function projectUserCostInsert($input){
        $res = [];
        foreach ($input as $k => $v) {
            $res[$k] = $v;
        }

        try {
            $data = ProjectUser::create($res);
            if($data){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function projectUserCostEdit($input){
        $res = [];
        foreach ($input as $k => $v) {
            $res[$k] = $v;
        }

        unset($res['id']);
        try {
            $data = ProjectUser::where('id',$input['id'])->update($res);
            if($data){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function editCost($input,$project_id,$user_id){
        $input = json_decode($input);
        $type = '';
        $res = [];
        foreach ($input as $k => $v) {
            $type = $v->type;
            $arr = [];
            $arr['project_id'] = $project_id;
            $arr['user_id'] = $user_id;
            $arr['title'] = $v->title;
            $arr['price'] = $v->price;
            $arr['rate'] = $v->rate;
            $arr['total'] = $v->total;
            $arr['is_system'] = $v->is_system;
            $arr['type'] = $v->type;
            $arr['remarks'] = $v->remarks ?? '/';
            $res[] = $arr;
        }

        try {
            ProjectCost::where('project_id',$project_id)->where('type',$type)->delete();
            $data = ProjectCost::insert($res);
            if($data){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }
}